package wiki.mczoo.tpp;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.util.*;
import java.util.stream.Collectors;

public class Tpp extends JavaPlugin implements Listener {

    private TppCommandExecutor commandExecutor;
    private TppTabCompleter tabCompleter;

    // 存储离线玩家的传送目标
    private Map<UUID, Location> pendingTeleports = new HashMap<>();

    @Override
    public void onLoad() {
        commandExecutor = new TppCommandExecutor(this);
        tabCompleter = new TppTabCompleter();
    }

    @Override
    public void onEnable() {
        int pluginId = 24785; // <-- Replace with the id of your plugin!
        Metrics metrics = new Metrics(this, pluginId);

        getCommand("tpp").setExecutor(commandExecutor);
        getCommand("tpp").setTabCompleter(tabCompleter);
        getServer().getPluginManager().registerEvents(this, this);
        System.out.printf("\u001B[32m[TPP]插件已加载，定制插件可联系作者QQ2279881513\u001B[0m\n");
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        UUID playerUUID = player.getUniqueId();

        // 检查是否有待处理的传送任务
        if (pendingTeleports.containsKey(playerUUID)) {
            Location targetLocation = pendingTeleports.get(playerUUID);
            player.teleport(targetLocation);
            player.sendMessage("§a你被传送到了 §e(" + targetLocation.getBlockX() + ", " + targetLocation.getBlockY() + ", " + targetLocation.getBlockZ() + ") §a在 §e" + targetLocation.getWorld().getName());
            pendingTeleports.remove(playerUUID); // 传送完成后移除任务
        }
    }

    private static class TppCommandExecutor implements CommandExecutor {

        private final Tpp plugin;

        public TppCommandExecutor(Tpp plugin) {
            this.plugin = plugin;
        }

        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            if (cmd.getName().equalsIgnoreCase("tpp") && args.length == 5) {
                if (!(sender.hasPermission("tpp.use"))) {
                    sender.sendMessage("§c你没有权限使用这个指令。");
                    return true;
                }

                String playerName = args[0];
                double x, y, z;
                String worldName = args[4];

                try {
                    x = Double.parseDouble(args[1]);
                    y = Double.parseDouble(args[2]);
                    z = Double.parseDouble(args[3]);
                } catch (NumberFormatException e) {
                    sender.sendMessage("§c坐标无效。");
                    return true;
                }

                // 获取目标世界
                World targetWorld = Bukkit.getWorld(worldName);
                if (targetWorld == null) {
                    sender.sendMessage("§c世界名无效。可用世界： " + getWorldNames());
                    return true;
                }

                // 获取目标玩家
                Player targetPlayer = Bukkit.getPlayer(playerName);
                Location location = new Location(targetWorld, x, y, z);

                if (targetPlayer != null) {
                    // 玩家在线，直接传送
                    targetPlayer.teleport(location);
                    sender.sendMessage("§a正在将 §e" + targetPlayer.getName() + " §a传送到 §e(" + x + ", " + y + ", " + z + ") §a在 §e" + targetWorld.getName());
                } else {
                    // 玩家离线，存储传送任务
                    UUID playerUUID = Bukkit.getOfflinePlayer(playerName).getUniqueId();
                    plugin.pendingTeleports.put(playerUUID, location);
                    sender.sendMessage("§a已为 §e" + playerName + " §a设置传送目标为 §e(" + x + ", " + y + ", " + z + ") §a在 §e" + targetWorld.getName() + " §a（将在玩家上线时生效）");
                }

                return true;
            } else {
                sender.sendMessage("§c用法：/tpp <玩家> <x> <y> <z> <世界>");
                return true;
            }
        }

        private String getWorldNames() {
            return Bukkit.getWorlds().stream()
                    .map(World::getName)
                    .collect(Collectors.joining(", "));
        }
    }

    private static class TppTabCompleter implements TabCompleter {

        @Override
        public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
            if (cmd.getName().equalsIgnoreCase("tpp")) {
                if (args.length == 1) {
                    // 自动补全玩家名（包括离线玩家）
                    return getPlayerNames(args[0]);
                } else if (args.length == 5) {
                    // 自动补全世界名称
                    return getWorldNames(sender);
                }
            }
            return new ArrayList<>();
        }

        private List<String> getPlayerNames(String startWith) {
            // 获取所有玩家名（包括离线玩家）
            List<String> playerNames = Arrays.stream(Bukkit.getOfflinePlayers())
                    .map(offlinePlayer -> offlinePlayer.getName()) // 直接从 OfflinePlayer 获取名字
                    .filter(name -> name != null && name.toLowerCase().startsWith(startWith.toLowerCase()))
                    .limit(20) // 限制返回结果最多20个
                    .collect(Collectors.toList());

            // 检查是否需要添加提示信息
            if (playerNames.size() == 20) {
                // 创建一个新的列表，确保提示信息在最下方
                List<String> finalList = new ArrayList<>(playerNames);
                finalList.add("<只显示前20位玩家>");
                return finalList;
            }

            return playerNames;
        }

        private List<String> getWorldNames(CommandSender sender) {
            return Bukkit.getWorlds().stream()
                    .map(World::getName)
                    .collect(Collectors.toList());
        }
    }
}